package com.gjm.ai.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.Duration;
import java.util.Date;

@RestController
public class SSMController {

    @GetMapping("/data")
    public void data(HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType("text/event-stream;charset=utf-8");
        PrintWriter writer = response.getWriter();

        String str = "";
        for (int i = 0; i < 10; i++) {
            str = "data: " + new Date() + "\n\n";
            writer.write(str);
            writer.flush();
            Thread.sleep(1000L);
        }
    }

    @GetMapping("/retry")
    public void retry(HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType("text/event-stream;charset=utf-8");
        PrintWriter writer = response.getWriter();

        String str = "retry: 2000\n"; //前端每隔 2000ms 重新发送请求
        str += "data: " + new Date() + "\n\n"; //每条消息必须以 data 结尾
        writer.write(str);
        writer.flush();
    }

    @GetMapping("/event")
    public void event(HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType("text/event-stream;charset=utf-8");
        PrintWriter writer = response.getWriter();

        for (int i = 0; i < 10; i++) {
            String str = "event: foo\n"; //自定义事件
            str += "data: " + new Date() + "\n\n";
            writer.write(str);
            writer.flush();
            Thread.sleep(1000L);
        }
    }

    @GetMapping("/end")
    public void end(HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType("text/event-stream;charset=utf-8");
        PrintWriter writer = response.getWriter();

        for (int i = 0; i < 10; i++) {
            String str = "event: foo\n";
            str += "data: " + new Date() + "\n\n";
            writer.write(str);
            writer.flush();
            Thread.sleep(1000L);
        }

        writer.write("event: end\ndata: EOF\n\n"); //结束
        writer.flush();
    }

    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> stream() {
        return Flux.interval(Duration.ofSeconds(1)).map(s -> {
            return new Date().toString();
        });
    }
}
